package com.lagou.edu.controller;

import com.lagou.edu.client.MailFeignClient;
import com.lagou.edu.constant.CodeConstant;
import com.lagou.edu.service.impl.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 陶肖寅
 * @version V1.0
 * <p>
 *     验证码接口类
 * @date 2020-05-06 13:25
 * @email fromlx@126.com
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 * </p>
 */
@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    CodeService codeService;
    @Autowired
    MailFeignClient mailFeignClient;
    /**
     * 生成验证码并发送到对应邮箱，成功true，失败 false
     * @param email 邮件地址
     * @return true/false
     */
    @GetMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email){
        try {
            //step-1 生成随机6位验证码。
            String code = codeService.generateCode();
            //step-2 将验证码存放到redis中。失效时间10分钟(10*60*60)
            codeService.saveCode(email,code);
            //step-3 发送邮件到指定邮件
            mailFeignClient.send(email,code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }

    /**
     * 校验验证码是否正确
     * @param email 邮件
     * @param code 验证码
     * @return 执行结果 0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email,
                            @PathVariable("code") String code){
        try {
            // step-1 获取验证码。
            String oldCode = codeService.getCode(email);
            // step-2 验证码是否正确
            if (oldCode == null) {
                return CodeConstant.TIMEOUT;

            }else if (!code.equals(oldCode)) {
                return CodeConstant.ERROR;
            }
            return CodeConstant.RIGHT;
        }catch (Exception e) {
            return  CodeConstant.ERROR;
        }
    }
}
